package com.example.testdb;

import com.mongodb.MongoClientSettings;
import com.mongodb.ServerAddress;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import org.bson.Document;
import org.bson.conversions.Bson;

import java.util.Arrays;

public class MongoDBExample {
    public static void main(String[] args) {
        // 连接到MongoDB服务器
        MongoClient mongoClient = MongoClients.create(
                MongoClientSettings.builder()
                        .applyToClusterSettings(builder ->
                                builder.hosts(Arrays.asList(new ServerAddress("localhost", 27017))))
                        .build());

        // 创建数据库和集合
        MongoDatabase database = mongoClient.getDatabase("test");
        MongoCollection<Document> collection = database.getCollection("myCollection");

        // 查看集合
        System.out.println("集合名称： " + collection.getNamespace().getCollectionName());

        // 插入文档
        Document document = new Document("name", "张三")
                .append("age", 30)
                .append("city", "北京");
        collection.insertOne(document);

        // 查看集合中的文档
        FindIterable<Document> documents = collection.find();
        for (Document doc : documents) {
            System.out.println(doc.toJson());
        }

        // 更新集合中的文档
        Bson filter = Filters.eq("name", "张三");
        Bson update = Updates.set("age", 31);
        collection.updateOne(filter, update);

        // 删除集合中的指定文档
        collection.deleteOne(filter);

        // 关闭连接
        mongoClient.close();
    }
}
